<?php

if (!defined('UC_FILESYSTEM_ROOT')) 
{
    define('UC_FILESYSTEM_ROOT', dirname(__FILE__) . '/');
    require_once UC_FILESYSTEM_ROOT . 'UC_PHPFileSystemAutoloader.php';
}

class UC_PHPFile extends UC_PHPFileSystemElement
{
    public function __construct($path)
    {
        parent::__construct($path);
    }
    
    public function delete()
    {
        set_error_handler(array('UC_PHPFile', 'error_handler'));
        if(!unlink($this->get_path()))
        {
            throw new UC_PHPFileSystemException(
                'Failed to delete file.');
        }
        restore_error_handler();
    }
    
    public function open_as_text_stream($IO_mode)
    {
        
    }
    
    public function set_extension($extension)
    {
        $new_name = $this->get_name() . '.' . $extension;
        rename($this->get_path(), 
            $this->get_parent_directory() . '/' . $new_name);
    }
    
    private static function error_handler($errno, $errstr, $errfile, $errline)
    {
        if(strpos($errstr, 'Permission denied'))
        {
            $trc = debug_backtrace();
            if(isset($trc[2]['function']))
            {
                if($trc[2]['function'] == 'delete')
                {
                    throw new UC_PHPFileSystemException(
                        'Unable to delete file: permission denied' 
                        . ' in ' . $errfile . ' on line ' . $errline);
                }
            }
        }
        
        return false;
    }
}

?>
